#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
#include <ctime>

#define NUM 6
template <class T>
class PC
{
public:
    PC(int cap = NUM) : _cap(cap)
    {
        pthread_mutex_init(&lock, nullptr);
        pthread_cond_init(&_empty, nullptr);
        pthread_cond_init(&_full, nullptr);
    }

    void Push(const T &in)
    {
        pthread_mutex_lock(&lock);
        while (full())
        {
            pthread_cond_wait(&_full, &lock);
        }
        q.push(in);
        pthread_cond_signal(&_empty);
        pthread_mutex_unlock(&lock);
    }
    void Pop(T &out)
    {
        pthread_mutex_lock(&lock);
        while (empty())
        {
            pthread_cond_wait(&_empty, &lock);
        }
        out = q.front();
        q.pop();
        pthread_cond_signal(&_full);
        pthread_mutex_unlock(&lock);
    }
    ~PC()
    {
        _cap = 0;
        pthread_mutex_destroy(&lock);
        pthread_cond_destroy(&_full);
        pthread_cond_destroy(&_empty);
    }

private:
    bool empty()
    {
        return q.empty();
    }
    bool full()
    {
        return q.size() == _cap;
    }

private:
    std::queue<T> q;
    int _cap;
    pthread_mutex_t lock;
    pthread_cond_t _empty;
    pthread_cond_t _full;
};
